﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlServerCe;
using System.Data.SqlClient;
using System.Data;
using Microsoft.Win32;
using System.IO;

namespace TAMSUP
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class form : Window
    {
        private string ID = "";
        private bool isUbah = false;
        private DataSet ubah = new DataSet();
        private int count;
        public form()
        {
            InitializeComponent();
        }

        public form(string ID)
        {
            this.ID = ID;
            isUbah = true;
            InitializeComponent();
            label1.Content = "Ubah Reklame";
            addButton.Content = "Edit";
            cancelButton.Content = "Cancel";
            Title = "TAMS UP :: Form :: Ubah Reklame";
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //System.Windows.Data.CollectionViewSource contactPersonViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("contactPersonViewSource")));
            //contactPersonViewSource.View.MoveCurrentToFirst();
            homeWindow.Con.Open();

            SqlDataAdapter da = new SqlDataAdapter("select * from reklame where ID_Reklame = '" + ID + "';", homeWindow.Con);
            ubah = new DataSet();
            da.Fill(ubah, "Daftar Reklame");

            tempoDate.SelectedDate = DateTime.Now;

            if (isUbah)
            {
                jenisText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(2).ToString();
                alamatText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(3).ToString();
                kotaText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(4).ToString();
                provinsiText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(5).ToString();
                ukuranText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(1).ToString();
                sewaText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(9).ToString();
                pajakText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(6).ToString();
                keteranganText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(11).ToString();
                tempoDate.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(7).ToString();
                pictureBox.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(13).ToString();
                priceText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(10).ToString();
                lokasiText.Text = ubah.Tables["Daftar Reklame"].Rows[0].ItemArray.ElementAt(8).ToString();
            }
            homeWindow.Con.Close();
        }

        private void restart()
        {
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            jenisText.Text = "";
            jenisText.Background = validColor;
            alamatText.Text = "";
            alamatText.Background = validColor;
            kotaText.Text = "";
            kotaText.Background = validColor;
            provinsiText.Text = "";
            provinsiText.Background = validColor;
            ukuranText.Text = "";
            ukuranText.Background = validColor;
            sewaText.Text = "";
            sewaText.Background = validColor;
            pajakText.Text = "";
            pajakText.Background = validColor;
            lokasiText.Text = "";
            lokasiText.Background = validColor;
            priceText.Text = "";
            priceText.Background = validColor;
            keteranganText.Text = "";
            tempoDate.SelectedDate = DateTime.Now;
        }

        private Boolean errorChecking()
        {
            Boolean valid = true;
            Brush invalidColor = new SolidColorBrush(Color.FromRgb(255, 225, 0));
            Brush ValidColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            int temp;
            if ((jenisText.Text == "") || (jenisText.Text.Length > 50))
            {
                jenisText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                jenisText.Background = ValidColor;
            }
            if ((alamatText.Text == "")  || (alamatText.Text.Length > 50))
            {
                alamatText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                alamatText.Background = ValidColor;
            }
            if ((kotaText.Text == "")  || (kotaText.Text.Length > 50))
            {
                kotaText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                kotaText.Background = ValidColor;
            }
            if ((provinsiText.Text == "") || (provinsiText.Text.Length > 50))
            {
                provinsiText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                provinsiText.Background = ValidColor;
            }
            if ((ukuranText.Text == "") || (ukuranText.Text.Length > 50))
            {
                ukuranText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                ukuranText.Background = ValidColor;
            }
            if (sewaText.Text == "")
            {
                sewaText.Background = invalidColor;
                if (valid) valid = false;
            }
            else if (!Int32.TryParse(sewaText.Text.ToString(), out temp))
            {
                sewaText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                sewaText.Background = ValidColor;
            }
            if (pajakText.Text == "" || !Int32.TryParse(pajakText.Text.ToString(), out temp))
            {
                pajakText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                pajakText.Background = ValidColor;
            }
            if (lokasiText.Text == "" || !Int32.TryParse(lokasiText.Text.ToString(), out temp))
            {
                lokasiText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                lokasiText.Background = ValidColor;
            }
            if (priceText.Text == "" || !Int32.TryParse(priceText.Text.ToString(), out temp))
            {
                priceText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                priceText.Background = ValidColor;
            }
            if (!valid)
            {
                MessageBox.Show("Ada kesalahan pengisian informasi tambah reklame.\nSelain keterangan, tidak boleh ada yang kosong atau lebih dari 50 karakter.", "Invalid Information");
            }
            return valid;
        }

        private void browseButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "Pilih Foto";
            dialog.InitialDirectory = @"c:\";
            dialog.Filter = "Gambar (*.jpg, *.bmp, *.png, *.tif) |*.jpg;*.bmp;*.png;*.tif";
            dialog.FilterIndex = 1;
            dialog.RestoreDirectory = false;
            bool? dialogResult = dialog.ShowDialog();
            if (dialogResult.HasValue && dialogResult.Value)
            {
                //User clicked OK
                pictureBox.Text = dialog.FileName;
            }

        }

        private void previewButton_Click(object sender, RoutedEventArgs e)
        {
            previewWindow preview;
            if (pictureBox.Text != "Tekan browse untuk memilih file gambar yang sesuai")
            {
                preview = new previewWindow(pictureBox.Text);
                preview.Visibility = Visibility.Visible;
            }
            else
            {
                MessageBox.Show("Pilih file gambar terlebih dahulu dengan menekan tombol 'Browse'", "Error: No File");
            }
        }

        private void pictureBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            if (errorChecking())
            {
                try
                {
                    homeWindow.Con.Open();
                    if (!isUbah)
                    {
                        if (pictureBox.Text != "Tekan browse untuk memilih file gambar yang sesuai")
                        {
                            string _Date = tempoDate.SelectedDate.Value.ToString("M/d/yyyy");

                            string _Insert = @"insert into Reklame (ID_Reklame, Ukuran, Jenis, Alamat, Kota, Provinsi, Pajak, Tanggal_Jatuh_Tempo_Pajak, Harga_Sewa, Keterangan, PriceList, Harga_Sewa_Lokasi)
                                  Values('R" + "','" + ukuranText.Text + "','" + jenisText.Text + "','" +
                                                     alamatText.Text + "','" + kotaText.Text + "','" + provinsiText.Text + "','" +
                                                     pajakText.Text + "','" + _Date + "','" + sewaText.Text + "','" + keteranganText.Text + "','" + priceText.Text + "','" + lokasiText.Text + "')";

                            SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                            _cmd.ExecuteNonQuery();
                            saveImage();
                            MessageBox.Show("Berhasil menambahkan sebuah reklame baru", "New Advertisement");
                        }
                        else
                        {
                            string _Date = tempoDate.SelectedDate.Value.ToString("M/d/yyyy");

                            string _Insert = @"insert into Reklame (ID_Reklame, Ukuran, Jenis, Alamat, Kota, Provinsi, Pajak, Tanggal_Jatuh_Tempo_Pajak, Harga_Sewa, Keterangan, PriceList, Harga_Sewa_Lokasi)
                                  Values('R" + "','" + ukuranText.Text + "','" + jenisText.Text + "','" +
                                                     alamatText.Text + "','" + kotaText.Text + "','" + provinsiText.Text + "','" +
                                                     pajakText.Text + "','" + _Date + "','" + sewaText.Text + "','" + keteranganText.Text + "','" + priceText.Text + "','" + lokasiText.Text + "')";

                            SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                            _cmd.ExecuteNonQuery();

                            SqlDataAdapter da = new SqlDataAdapter("select IDENT_CURRENT('Reklame')", homeWindow.Con);
                            DataSet ds = new DataSet();
                            da.Fill(ds, "ID");

                            string ss = ds.Tables["ID"].Rows[0].ItemArray.ElementAt(0).ToString();

                            // Specify a "currently active folder"
                            string activeDir = "\\\\SERVER-PC\\Users\\Public\\Pictures";

                            //Create a new subfolder under the current active folder
                            string newPath = System.IO.Path.Combine(activeDir, "images" + ss);

                            //Set insert query
                            string qry = "update Reklame set PathGambar=@PathGambar where ID='" + ss + "'";

                            //Initialize SqlCommand object for insert.
                            SqlCommand SqlCom = new SqlCommand(qry, homeWindow.Con);
                            SqlCom.Parameters.Add(new SqlParameter("@PathGambar", (object)newPath));

                            // Create the subfolder
                            System.IO.Directory.CreateDirectory(newPath);
                            SqlCom.ExecuteNonQuery();
                            MessageBox.Show("Berhasil menambahkan sebuah reklame baru", "New Advertisement");
                        }
                        homeWindow.Con.Close();
                        homeWindow.top.refresh();
                        restart();
                    }
                    else
                    {
                        string _Date = tempoDate.SelectedDate.Value.ToString("M/d/yyyy");

                        string _Insert = @"update Reklame
                                    set Ukuran = '" + ukuranText.Text + "', Jenis = '" + jenisText.Text + "',  Alamat = '" + alamatText.Text +
                                                            "',  Kota = '" + kotaText.Text + "',  Provinsi = '" + provinsiText.Text + "',  Pajak = '" + pajakText.Text +
                                                            "',  Harga_Sewa = '" + sewaText.Text + "',  Tanggal_Jatuh_Tempo_Pajak = '" + _Date +
                                                            "', Keterangan = '" + keteranganText.Text + "',  PriceList = '" + priceText.Text + "', Harga_Sewa_Lokasi = '" + lokasiText.Text + "'" +
                                                            "where ID_Reklame = '" + ID + "';";

                        SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();

                        MessageBox.Show("Berhasil mengubah sebuah reklame", "Update Advertisement");
                        homeWindow.top.Focus();
                        homeWindow.Con.Close();
                        homeWindow.top.refresh();
                        this.Close();
                    }
                }
                catch (SqlException sqle)
                {
                    MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                }
            }
        }

        private void tempoDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            //tempoDate.DisplayDate = tempoDate.SelectedDate.ToString;
        }

        private void Window_Unlooaded(object sender, RoutedEventArgs e)
        {

        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (isUbah)
            {
                homeWindow.top.Focus();
                homeWindow.top.refresh();
                this.Close();
            }
            else
            {
                restart();
            }
        }

        private void formWindow_Closed(object sender, EventArgs e)
        {
            homeWindow.top.Focus();
            homeWindow.top.refresh();
        }

        private void saveImage()
        {
            //Read Image Bytes into a byte array
            byte[] imageData = ReadFile(pictureBox.Text);

            //Initialize SQL Server Connection

            SqlDataAdapter da = new SqlDataAdapter("select IDENT_CURRENT('Reklame')", homeWindow.Con);
            DataSet ds = new DataSet();
            da.Fill(ds, "ID");

            string ss = ds.Tables["ID"].Rows[0].ItemArray.ElementAt(0).ToString();

            // Specify a "currently active folder"
            string activeDir = "\\\\SERVER-PC\\Users\\Public\\Pictures";

            //Create a new subfolder under the current active folder
            string newPath = System.IO.Path.Combine(activeDir, "images" + ss);

            //Set insert query
            string qry = "update Reklame set PathGambar=@PathGambar, Gambar=@Gambar where ID='" + ss + "'";

            //Initialize SqlCommand object for insert.
            SqlCommand SqlCom = new SqlCommand(qry, homeWindow.Con);

            SqlCom.Parameters.Add(new SqlParameter("@PathGambar", (object)newPath));

            // Create the subfolder
            System.IO.Directory.CreateDirectory(newPath);

            string namafile = "images" + count + pictureBox.Text.ElementAt(pictureBox.Text.Count() - 4) + 
                pictureBox.Text.ElementAt(pictureBox.Text.Count() - 3) + pictureBox.Text.ElementAt(pictureBox.Text.Count() - 2) + 
                pictureBox.Text.ElementAt(pictureBox.Text.Count() - 1);

            newPath = System.IO.Path.Combine(newPath, namafile);

            saveFile(imageData,newPath);

            //We are passing Original Image Path and 
            //Image byte data as SQL parameters.
                
            SqlCom.Parameters.Add(new SqlParameter("@Gambar", (object)imageData));

            //Open connection and execute insert query.
            SqlCom.ExecuteNonQuery();
            homeWindow.Con.Close();
        }

        byte[] ReadFile(string sPath)
        {
            //Initialize byte array with a null value initially.
            byte[] data = null;

            //Use FileInfo object to get file size.
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;

            //Open FileStream to read file
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

            //Use BinaryReader to read file stream into byte array.
            BinaryReader br = new BinaryReader(fStream);

            //When you use BinaryReader, you need to supply number of bytes 
            //to read from file.
            //In this case we want to read entire file. 
            //So supplying total number of bytes.
            data = br.ReadBytes((int)numBytes);

            return data;
        }

        void saveFile(byte[] data, string sPath)
        {
            //Open FileStream to read file
            FileStream fStream = new FileStream(sPath, FileMode.Create, FileAccess.ReadWrite);

            //Use BinaryReader to read file stream into byte array.
            BinaryWriter br = new BinaryWriter(fStream);

            br.Write(data);

            fStream.Close();
        }

        private string addNol(int x)
        {
            string temp = "";
            string angka = x.ToString();

            if (angka.Count() == 4)
            {
                temp = "0";
            }
            else if (angka.Count() == 3)
            {
                temp = "00";
            }
            else if (angka.Count() == 2)
            {
                temp = "000";
            }
            else if (angka.Count() == 1)
            {
                temp = "0000";
            }
            Console.WriteLine(temp);
            return temp;
        }

        //public void SetMyCustomFormat()
        //{
        //    // Set the Format type and the CustomFormat string.
        //    tempoDate.SelectedDateForm;
        //    dateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd";
        //}
    }
}
